from rest_framework.views import APIView
from .serializers import UploadImageSerializer
from rest_framework.response import Response
from shortuuid import uuid
import os
from django.conf import settings

class UploadImageAPIView(APIView):
    def post(self,request):
        serializer = UploadImageSerializer(data=request.data)
        if serializer.is_valid():
            file = serializer.validated_data['image']
            filename = uuid() + os.path.splitext(file.name)[-1]  ## uuid + 图片后缀
            path = settings.MEDIA_ROOT / filename
            try:
                with open(path,'wb') as fb:
                    for chunk in file.chunks():
                        fb.write(chunk)
            except Exception as e:
                return Response({
                    "error":1,
                    "message":f"图片保存失败{e}"
                })
            file_url = settings.MEDIA_URL + filename
            return Response({
                "error":0,
                "data":{
                    "url":file_url,
                    "alt":file.name,
                    "href":file_url
                }
            })
        else:
            print(serializer.errors)
            return Response({
                "error":1,
                "message":list(serializer.errors.values())[0][0]
            })
        ##ErrorDetail 对象本身就是 “带有代码的错误字符串对象”，直接当作字符串用会返回它的 string 部分。
